package com.jgp.security.service;

import com.jgp.common.pojo.TreeBean;
import com.jgp.common.utils.InsertUpdateDelete;
import com.jgp.common.utils.JGPUtil;
import com.jgp.security.secmodel.SecInstitution;
import com.jgp.security.secmodel.SecInstitutionUser;
import com.jgp.security.secmodel.SecUser;
import com.jgp.security.secrepository.SecInstitutionRepository;
import com.jgp.security.secrepository.SecInstitutionUserRepository;
import com.jgp.security.secrepository.SecUserRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 项目   jgp-cloud-parent
 * 作者   loufei
 * 时间   2019-11-02
 */
@Service
@Transactional(transactionManager = "secondTransactionManager",readOnly = true)
public class SecInstitutionUserService {
    
    @Lazy
    @Autowired
    private SecInstitutionUserRepository repository;
    @Lazy
    @Autowired
    private SecInstitutionRepository institutionRepository;
    @Lazy
    @Autowired
    private SecUserRepository userRepository;
    @Lazy
    @Autowired
    private SecUserService secUserService;

    public List<Long> queryInstitutionIds(String userId) {
        if(StringUtils.isBlank(userId)) return null;
        List<SecInstitutionUser> institutionUsers = repository.findByUserId(userId);
        List<Long> ids = institutionUsers.stream().map(SecInstitutionUser::getInstitutionId).collect(Collectors.toList());
        return ids;
    }
    
    /**
     * 查询指定人从属机构
     *
     * @param userId
     * @return 返回指定人的机构树，不存在无关机构
     */
    public List<TreeBean> queryPrivateInstitutionTree(String userId) {
        List<Long> ids = queryInstitutionIds(userId);
        if(Objects.isNull(ids)) return new ArrayList<>();
        return institutionRepository.queryTreeFromBottomToTop(ids);
    }
    
    @Transactional(transactionManager = "secondTransactionManager")
    public void modifyUserInstitution(String userId, List<Long> institutionIds) {
        List<SecInstitutionUser> roleUsers = repository.findByUserId(userId);
        List<Long> persistInstitutionIds = roleUsers.stream().map(SecInstitutionUser::getInstitutionId).collect(Collectors.toList());
        InsertUpdateDelete<Long> insertUpdateDelete = JGPUtil.iud(institutionIds, persistInstitutionIds);
        
        if(insertUpdateDelete.getDeletes().size()>0){
            repository.deleteByUserIdAndInstitutionIdIn(userId,insertUpdateDelete.getDeletes());
        }
        
        if(insertUpdateDelete.getInserts().size()>0){
            List<SecInstitutionUser> newItems = new ArrayList<>();
            for (Long institutionId : insertUpdateDelete.getInserts()) {
                SecInstitutionUser rm = new SecInstitutionUser();
                rm.setUserId(userId);
                rm.setInstitutionId(institutionId);
                newItems.add(rm);
            }
            repository.createInBatch(newItems);
        }
        //分配组织机构，默认给人员表default_institution_id赋值最小单位id
        secUserService.updateDefaultInstitutionId(userId,Collections.max(institutionIds));
    }
    
    public List<SecInstitution> queryInstitutions(String userId) {
        List<Long> ids = queryInstitutionIds(userId);
        return institutionRepository.read(ids);
    }
    
    public List<String> queryUserIds(Long institutionId){
        if(Objects.isNull(institutionId)) return null;
        List<SecInstitutionUser> institutionUsers = repository.findByInstitutionId(institutionId);
        return institutionUsers.stream().map(SecInstitutionUser::getUserId).collect(Collectors.toList());
    }
    
    public List<SecUser> queryUsers(Long institutionId){
        List<String> ids = queryUserIds(institutionId);
        return userRepository.readAll(ids);
    }
    
    public List<String> queryUserIds(List<Long> institutionIds) {
        List<SecInstitutionUser> institutionUsers = repository.findByInstitutionIdIn(institutionIds);
        return institutionUsers.stream().map(SecInstitutionUser::getUserId).distinct().collect(Collectors.toList());
    }
}
